package com.lagou.edu.service.impl;

import com.lagou.edu.service.OrderMessage;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * @author stevejson
 */
@Service
public class OrderMessageImpl implements OrderMessage {
    @Resource
    private RabbitTemplate rabbitTemplate;

    @Override
    public Boolean publisherCreateOrder(Integer id) {
        try{

            boolean sendFlag = rabbitTemplate.invoke(operations -> {
                MessageProperties properties = MessagePropertiesBuilder.newInstance()
                        .setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN)
                        .setContentEncoding("utf-8")
                        .setDeliveryMode(MessageDeliveryMode.PERSISTENT)
                        .build();
                Message msg = MessageBuilder.withBody(String.valueOf(id).getBytes(StandardCharsets.UTF_8)).andProperties(properties).build();
                rabbitTemplate.send("ex.order", "key.order", msg);
                return rabbitTemplate.waitForConfirms(5_000);
            });
            return sendFlag;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }

    }
}
